<template>
    <ww-open-data class="open-data is-openid" v-if="isOpenData && openid" ref="openData" :type="type" :openid="openid"></ww-open-data> 
    <span v-else class="open-data is-name">{{ name }}</span>
</template>

<script>
import _ from 'lodash'
/* util */
import { isOpenData, isDevelopment, getIsOpenData } from '@src/util/platform'
import { getRootWindow } from '@src/util/dom'
import Platform from '@src/platform'

const rootWindow = getRootWindow(window)

export default {
  name: 'open-data',
  props: {
    type: {
      type: String,
      default: 'userName'
    },
    openid: {
      type: String | Object,
      default: ''
    },
    name: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      isOpenData: getIsOpenData()
    }
  },
  watch: {
    openid: {
      handler(newValue) {
        newValue && this.bind()
      }
    }
  },
  created () {
    this.$eventBus.$on('wx-sign-done', this.bind);
  },
  destroyed () {
    this.$eventBus.$off('wx-sign-done', this.bind);
  },
  mounted () {
    this.bind()
  },
  methods: {
    bind() {
      if(!this.isOpenData) return
      
      this.checkSession()
      
      this.$nextTick(()=>{
        rootWindow.WWOpenData && rootWindow.WWOpenData.bind(this.$refs.openData)
      })
    },
    checkSession: _.debounce(function() {
      try {
        if (
          (!rootWindow.WWOpenData && !rootWindow.WWOpenData.checkSession) 
          || isDevelopment()
        ) return
        
        rootWindow.WWOpenData.checkSession({
          success() {
            console.info('open-data 登录态校验成功')
          },
          fail() {
            console.error('open-data 登录态过期')
            // 跳转到扫码登录
            // Platform.notification({
            //   message: '登录已过期，请重新扫码登录',
            //   type: 'warning'
            // })
            // setTimeout(() => {
            //   window.location.href = '/account/wechatLogin';
            // }, 500);
          },
        })
      } catch (error) {
        console.warn(error)
      }
      
    }, 1500),
    config(config) {
      return new Promise((resolve, reject) => {
        rootWindow.wx.config(config)
        rootWindow.wx.ready(resolve)
        rootWindow.wx.error(reject)
      })
    },
    agentConfig(config) {
      return new Promise((success, fail) => {
        rootWindow.wx.agentConfig({ ...config, success, fail })
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.open-data {
  // display: inline-flex;
  // margin-right: 12px;
}
</style>
